﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace msilgc.common {
    public static class EnvironmentFinder {
        public static string GetValueTryDefault(string key, IEnumerable<string> defaultsToTry) {
            return GetValueTryDefault(new[] {key}, defaultsToTry);
        }

        public static string GetValueTryDefault(IEnumerable<string> keys, IEnumerable<string> defaultsToTry) {
            var valuesToTry = defaultsToTry;
            bool foundEnv = false;
            foreach (var key in keys) {
                string environmentValue = Environment.GetEnvironmentVariable(key);
                if (!string.IsNullOrEmpty(environmentValue)) {
                    foundEnv = true;
                    valuesToTry = new[] {environmentValue}.Union(valuesToTry);
                }
            }
            var matching = valuesToTry.Where(TestPath);
            foreach (string match in matching) {
                return match;
            }
            if (!foundEnv) {
                throw new Exception(keys.First() + " environment variable not set.");
            }
            throw new Exception(keys.First() + " environment variable points to an invalid path");
        }

        private static bool TestPath(string path) {
            return 
                new DirectoryInfo(path).Exists ||
                new FileInfo(path).Exists;
        }
    }
}